package com.hello.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.hello.common.core.domain.R;
import com.hello.common.core.utils.StringUtils;
import com.hello.common.core.utils.SpringUtils;
import com.hello.common.core.utils.poi.ExcelUtil;
import com.hello.common.core.web.controller.BaseController;
import com.hello.common.core.web.domain.AjaxResult;
import com.hello.common.core.web.page.TableDataInfo;
import com.hello.common.log.annotation.Log;
import com.hello.common.log.enums.BusinessType;
import com.hello.common.security.utils.SecurityUtils;
import com.hello.system.domain.SysDept;
import com.hello.system.domain.SysRole;
import com.hello.system.domain.SysUser;
import com.hello.system.api.dto.SysUserDTO;
import com.hello.system.api.model.LoginUser;
import com.hello.system.service.ISysConfigService;
import com.hello.system.service.ISysDeptService;
import com.hello.system.service.ISysPermissionService;
import com.hello.system.service.ISysPostService;
import com.hello.system.service.ISysRoleService;
import com.hello.system.service.ISysUserService;
import com.hello.system.utils.WxApiUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户信息
 * 
 * @author hello
 */
@Slf4j
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class SysUserController extends BaseController
{
    private final ISysUserService userService;

    private final ISysRoleService roleService;

    private final ISysDeptService deptService;

    private final ISysPostService postService;

    private final ISysPermissionService permissionService;

    private final ISysConfigService configService;

    /**
     * 获取用户列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException
    {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username)
    {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        
        // 将SysUser转换为SysUserDTO
        SysUserDTO userDTO = new SysUserDTO();
        userDTO.setUserId(sysUser.getUserId());
        userDTO.setDeptId(sysUser.getDeptId());
        userDTO.setUserName(sysUser.getUserName());
        userDTO.setNickName(sysUser.getNickName());
        userDTO.setEmail(sysUser.getEmail());
        userDTO.setPhonenumber(sysUser.getPhonenumber());
        userDTO.setSex(sysUser.getSex());
        userDTO.setAvatar(sysUser.getAvatar());
        userDTO.setPassword(sysUser.getPassword());
        userDTO.setStatus(sysUser.getStatus());
        userDTO.setDelFlag(sysUser.getDelFlag());
        userDTO.setLoginIp(sysUser.getLoginIp());
        userDTO.setLoginDate(sysUser.getLoginDate());
        userDTO.setWxOpenid(sysUser.getWxOpenid());
        
        sysUserVo.setSysUser(userDTO);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }
    
    /**
     * 通过微信openid获取用户信息
     */
    @GetMapping("/wx/{code}")
    public R<LoginUser> getUserInfoByWxOpenid(@PathVariable("code") String code)
    {
        log.info("通过微信code获取用户信息: {}", code);
        
        try {
            // 检查是否直接传入openid (如果长度在28个字符以上，可能是openid)
            if (code != null && code.length() >= 28) {
                log.info("直接使用openid查询用户: {}", code);
                SysUser user = userService.selectUserByWxOpenid(code);
                
                if (user != null) {
                    LoginUser loginUser = new LoginUser();
                    loginUser.setUserid(user.getUserId());
                    loginUser.setUsername(user.getUserName());
                    
                    // 将SysUser转换为SysUserDTO
                    SysUserDTO userDTO = new SysUserDTO();
                    userDTO.setUserId(user.getUserId());
                    userDTO.setUserName(user.getUserName());
                    userDTO.setNickName(user.getNickName());
                    userDTO.setPassword(user.getPassword());
                    userDTO.setAvatar(user.getAvatar());
                    userDTO.setWxOpenid(user.getWxOpenid());
                    
                    loginUser.setSysUser(userDTO);
                    
                    log.info("通过openid直接查询到用户: {}", user.getUserName());
                    return R.ok(loginUser);
                }
                
                log.info("未查询到绑定该openid的用户");
                return R.fail("未查询到绑定该openid的用户");
            }
            
            // 获取微信工具类
            WxApiUtils wxApiUtils = SpringUtils.getBean(WxApiUtils.class);
            if (wxApiUtils == null) {
                log.error("获取WxApiUtils失败");
                return R.fail("系统错误，请联系管理员");
            }
            
            // 通过code获取openid
            JSONObject sessionResult = wxApiUtils.code2Session(code);
            if (sessionResult == null) {
                log.error("获取微信openid失败，code: {}", code);
                return R.fail("获取微信用户信息失败，请重新登录");
            }
            
            // 检查是否返回了错误码
            Integer errcode = sessionResult.getInteger("errcode");
            if (errcode != null && errcode != 0) {
                String errmsg = sessionResult.getString("errmsg");
                log.error("微信接口返回错误，错误码: {}, 错误信息: {}, code: {}", errcode, errmsg, code);
                
                // 特殊处理code已使用的错误
                if (errcode == 40163) {
                    return R.fail("登录凭证已失效，请重新获取");
                }
                
                return R.fail("获取微信用户信息失败: " + errmsg);
            }
            
            String openid = sessionResult.getString("openid");
            if (openid == null || openid.isEmpty()) {
                log.error("获取到的openid为空，code: {}", code);
                return R.fail("获取微信用户信息失败");
            }
            
            // 验证openid格式是否正确 (微信openid通常是28个字符)
            if (openid.length() < 20) {
                log.error("获取到的openid格式异常，长度过短: {}, code: {}", openid, code);
                return R.fail("获取微信用户信息失败，数据格式异常");
            }
            
            log.info("获取到微信openid: {}", openid);
            
            // 根据openid查询用户信息
            SysUser sysUser = userService.selectUserByWxOpenid(openid);
            if (sysUser == null)
            {
                log.info("微信用户不存在，openid: {}，自动注册新用户", openid);
                
                // 自动创建一个新用户
                sysUser = new SysUser();
                String randomSuffix;
                try {
                    // 生成更可靠的随机后缀
                    randomSuffix = openid.substring(openid.length() - 8); // 取openid后8位作为随机后缀
                } catch (Exception e) {
                    log.error("获取openid后缀异常: {}", e.getMessage());
                    randomSuffix = String.format("%08d", (int)(Math.random() * 100000000));
                }
                
                String userName = "wx_" + randomSuffix;
                String nickName = "微信用户" + randomSuffix;
                
                sysUser.setUserName(userName);
                sysUser.setNickName(nickName);
                sysUser.setWxOpenid(openid);
                // 设置随机密码
                String password = SecurityUtils.encryptPassword(openid.substring(0, 16));
                sysUser.setPassword(password);
                // 设置为普通用户
                sysUser.setDeptId(110L); // 使用默认部门ID
                sysUser.setStatus("0"); // 正常状态
                sysUser.setDelFlag("0"); // 未删除
                
                try {
                    // 检查用户名是否已存在，如果存在则生成新的用户名
                    int suffix = 1;
                    String baseUserName = userName;
                    while (!userService.checkUserNameUnique(sysUser)) {
                        userName = baseUserName + "_" + suffix;
                        sysUser.setUserName(userName);
                        suffix++;
                        // 防止无限循环
                        if (suffix > 10) {
                            log.error("无法生成唯一用户名，自动注册失败，openid: {}", openid);
                            return R.fail("系统错误，无法自动注册");
                        }
                    }
                    
                    log.info("开始注册微信用户，用户名: {}, openid后缀: {}", userName, randomSuffix);
                    boolean result = userService.registerUser(sysUser);
                    if (!result) {
                        log.error("微信用户自动注册失败，openid: {}", openid);
                        return R.fail("微信用户自动注册失败，请稍后重试");
                    }
                    log.info("微信用户自动注册成功，用户名: {}, openid: {}", sysUser.getUserName(), openid);
                    
                    // 重新获取用户信息
                    sysUser = userService.selectUserByWxOpenid(openid);
                    if (sysUser == null) {
                        log.error("微信用户注册后无法查询到用户信息，openid: {}", openid);
                        return R.fail("系统错误，请稍后重试");
                    }
                } catch (Exception e) {
                    log.error("微信用户自动注册异常，openid: {}, 错误: {}", openid, e.getMessage(), e);
                    return R.fail("微信用户自动注册失败：" + e.getMessage());
                }
            }
            
            log.info("微信用户存在，用户名: {}, openid: {}", sysUser.getUserName(), sysUser.getWxOpenid());
            
            // 角色集合
            Set<String> roles = permissionService.getRolePermission(sysUser);
            // 权限集合
            Set<String> permissions = permissionService.getMenuPermission(sysUser);
            LoginUser sysUserVo = new LoginUser();
            
            // 将SysUser转换为SysUserDTO
            SysUserDTO userDTO = new SysUserDTO();
            userDTO.setUserId(sysUser.getUserId());
            userDTO.setDeptId(sysUser.getDeptId());
            userDTO.setUserName(sysUser.getUserName());
            userDTO.setNickName(sysUser.getNickName());
            userDTO.setEmail(sysUser.getEmail());
            userDTO.setPhonenumber(sysUser.getPhonenumber());
            userDTO.setSex(sysUser.getSex());
            userDTO.setAvatar(sysUser.getAvatar());
            userDTO.setPassword(sysUser.getPassword());
            userDTO.setStatus(sysUser.getStatus());
            userDTO.setDelFlag(sysUser.getDelFlag());
            userDTO.setLoginIp(sysUser.getLoginIp());
            userDTO.setLoginDate(sysUser.getLoginDate());
            userDTO.setWxOpenid(sysUser.getWxOpenid());
            
            sysUserVo.setSysUser(userDTO);
            sysUserVo.setRoles(roles);
            sysUserVo.setPermissions(permissions);
            return R.ok(sysUserVo);
        } catch (Exception e) {
            log.error("获取微信用户信息异常", e);
            return R.fail("获取用户信息异常");
        }
    }

    /**
     * 注册用户信息
     */
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUserDTO sysUser)
    {
        String username = sysUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser"))))
        {
            return R.fail("当前系统没有开启注册功能！");
        }
        
        // 转换为SysUser对象
        SysUser user = new SysUser();
        user.setUserName(sysUser.getUserName());
        user.setNickName(sysUser.getNickName());
        user.setPassword(sysUser.getPassword());
        user.setEmail(sysUser.getEmail());
        user.setPhonenumber(sysUser.getPhonenumber());
        user.setSex(sysUser.getSex());
        user.setAvatar(sysUser.getAvatar());
        
        // 处理微信openid - 区分已获取的openid和临时code
        String wxOpenid = sysUser.getWxOpenid();
        if (wxOpenid != null && !wxOpenid.isEmpty()) {
            // 验证格式是否符合openid的规范（微信openid通常是28个字符）
            if (wxOpenid.length() < 20) {
                log.error("传入的wxOpenid格式异常，可能是无效code: {}", wxOpenid);
                return R.fail("参数格式错误，请重新获取微信登录凭证");
            }
            
            // 如果看起来像是一个openid（通常是28个字符的字符串），则直接使用
            if (wxOpenid.length() >= 28) {
                log.info("使用传入的openid: {}", wxOpenid);
                user.setWxOpenid(wxOpenid);
            } else {
                // 否则可能是传入了code，尝试获取openid
                log.info("注册用户时检测到可能是微信code，尝试获取openid: {}", wxOpenid);
                
                // 获取微信工具类并获取openid
                WxApiUtils wxApiUtils = SpringUtils.getBean(WxApiUtils.class);
                if (wxApiUtils != null) {
                    JSONObject sessionResult = wxApiUtils.code2Session(wxOpenid);
                    if (sessionResult != null) {
                        // 检查是否有错误码
                        Integer errcode = sessionResult.getInteger("errcode");
                        if (errcode != null && errcode != 0) {
                            String errmsg = sessionResult.getString("errmsg");
                            log.error("微信接口返回错误，错误码: {}, 错误信息: {}, code: {}", errcode, errmsg, wxOpenid);
                            
                            // 特殊处理code已使用的错误
                            if (errcode == 40163) {
                                log.error("微信登录凭证已失效，拒绝注册: {}", wxOpenid);
                                return R.fail("微信登录凭证已失效，请重新获取新的登录凭证");
                            }
                            
                            return R.fail("微信用户注册失败: " + errmsg);
                        }
                        
                        String openid = sessionResult.getString("openid");
                        if (openid != null && !openid.isEmpty()) {
                            log.info("获取到微信openid: {}", openid);
                            user.setWxOpenid(openid);
                            
                            // 检查该openid是否已存在
                            SysUser existUser = userService.selectUserByWxOpenid(openid);
                            if (existUser != null) {
                                log.warn("微信openid已存在: {}", openid);
                                return R.fail("该微信账号已经注册，请直接登录");
                            }
                        } else {
                            log.error("无法获取openid，微信注册失败");
                            return R.fail("微信用户注册失败");
                        }
                    } else {
                        log.error("无法获取微信会话信息，注册失败");
                        return R.fail("微信用户注册失败，无法获取会话信息");
                    }
                } else {
                    log.error("获取WxApiUtils失败，微信注册失败");
                    return R.fail("系统错误，请联系管理员");
                }
            }
        }
        
        try {
            if (!userService.checkUserNameUnique(user))
            {
                return R.fail("保存用户'" + username + "'失败，注册账号已存在");
            }
            boolean result = userService.registerUser(user);
            if (result) {
                // 增强微信注册日志，完整打印微信openid
                if (user.getWxOpenid() != null && !user.getWxOpenid().isEmpty()) {
                    log.info("微信用户注册成功: {}，完整openid: {}", user.getUserName(), user.getWxOpenid());
                } else {
                    log.info("用户注册成功: {}", user.getUserName());
                }
                return R.ok(true);
            } else {
                log.error("用户注册失败: {}", user.getUserName());
                return R.fail("用户注册失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("用户注册异常: {}, 错误信息: {}", user.getUserName(), e.getMessage(), e);
            // 针对微信用户注册失败的特殊处理
            if (user.getWxOpenid() != null && !user.getWxOpenid().isEmpty()) {
                return R.fail("微信用户注册失败，请稍后重试");
            }
            return R.fail("用户注册异常: " + e.getMessage());
        }
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = userService.selectUserById(SecurityUtils.getUserId());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            SysUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 绑定微信openid到用户
     */
    @PostMapping("/wx/bind")
    public R<Boolean> bindWxOpenid(@RequestParam("username") String username, 
                                  @RequestParam("openid") String openid)
    {
        log.info("绑定微信openid到用户请求: username={}, openid={}", username, openid);
        
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(openid)) {
            log.error("绑定微信openid参数错误，用户名或openid为空");
            return R.fail("用户名和微信openid不能为空");
        }
        
        try {
            // 查询用户是否存在
            SysUser user = userService.selectUserByUserName(username);
            if (user == null) {
                log.error("绑定微信openid失败，用户不存在: {}", username);
                return R.fail("用户不存在");
            }
            
            // 检查openid是否已绑定其他用户
            SysUser existUser = userService.selectUserByWxOpenid(openid);
            if (existUser != null && !existUser.getUserName().equals(username)) {
                log.error("绑定微信openid失败，openid已绑定其他用户: {}", existUser.getUserName());
                return R.fail("该微信账号已绑定其他用户");
            }
            
            // 更新用户的微信openid
            user.setWxOpenid(openid);
            user.setUpdateBy(username);
            boolean result = userService.updateUser(user) > 0;
            
            if (result) {
                log.info("绑定微信openid成功: username={}, openid={}", username, openid);
                return R.ok(true);
            } else {
                log.error("绑定微信openid失败，更新用户信息失败");
                return R.fail("绑定失败，请稍后重试");
            }
        } catch (Exception e) {
            log.error("绑定微信openid异常", e);
            return R.fail("绑定异常: " + e.getMessage());
        }
    }

    /**
     * 新增用户
     */
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user)
    {
        if (!userService.checkUserNameUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
        {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        log.info("修改用户信息开始, 用户ID: {}, 用户名: {}", user.getUserId(), user.getUserName());
        log.info("用户完整信息: {}", user.toString());
        log.info("用户roles字段: {}, 类型: {}", user.getRoles(), user.getRoles() != null ? user.getRoles().getClass().getName() : "null");
        log.info("用户roleIds字段: {}", user.getRoleIds());
        
        // 打印原始JSON字符串
        try {
            String jsonString = com.alibaba.fastjson.JSON.toJSONString(user);
            log.info("用户对象转换为JSON: {}", jsonString);
        } catch (Exception e) {
            log.error("转换用户对象为JSON时发生错误", e);
        }
        
        try {
            // 确保roles不为null
            if (user.getRoles() == null) {
                log.warn("用户roles为null，设置为空列表");
                user.setRoles(new ArrayList<>());
            }
            
            userService.checkUserAllowed(user);
            userService.checkUserDataScope(user.getUserId());
            if (!userService.checkUserNameUnique(user))
            {
                return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
            }
            else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user))
            {
                return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
            }
            else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
            {
                return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
            }
            user.setUpdateBy(SecurityUtils.getUsername());
            
            // 记录调用updateUser之前的对象状态
            log.info("调用updateUser前的用户对象：userId={}, userName={}, roles={}, roleIds={}", 
                     user.getUserId(), user.getUserName(), user.getRoles(), user.getRoleIds());
            
            // 如果roles为空但roleIds不为空，尝试从roleIds构建roles
            if ((user.getRoles() == null || user.getRoles().isEmpty()) && user.getRoleIds() != null && user.getRoleIds().length > 0) {
                log.info("从roleIds构建roles: {}", (Object)user.getRoleIds());
                List<SysRole> roles = new ArrayList<>();
                for (Long roleId : user.getRoleIds()) {
                    SysRole role = new SysRole();
                    role.setRoleId(roleId);
                    roles.add(role);
                }
                user.setRoles(roles);
                log.info("已从roleIds构建roles: {}", user.getRoles());
            }
            
            int result = userService.updateUser(user);
            log.info("修改用户结果: {}, 返回码: {}", result > 0 ? "成功" : "失败", result);
            return toAjax(result);
        } catch (Exception e) {
            log.error("修改用户异常", e);
            return error("修改用户异常: " + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds)
    {
        if (ArrayUtils.contains(userIds, SecurityUtils.getUserId()))
        {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId)
    {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
